package cn.cai.passwordencoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MyMD5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {

        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] tmp = digest.digest(rawPassword.toString().getBytes());
            return toHexString(tmp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(encode(rawPassword));
    }

    private String toHexString(byte[] tmp){
        StringBuilder builder = new StringBuilder();
        for (byte b : tmp){
            String s = Integer.toHexString(b & 0xFF);
            if (s.length() == 1){
                builder.append("0");
            }
            builder.append(s);
        }
        return builder.toString();
    }
}
